#include "RayTracer.h"


namespace RTRT
{
  RayTracer :: RayTracer()
  {
    
  }

  RayTracer :: RayTracer()
  {
    
  }

  int RayTracer :: rayTrace(Ray &ray, Color3f &a_Acc, int a_Depth, float a_RIndex, float a_Dist)
  {
    if (a_Depth > TRACEDEPTH) 
      return 0;
    
    // trace primary ray
    a_Dist = 100000000.0f;
    Vector3 pIntersect;
    Primitive *prim = 0;
    int result;
    
    // find the nearest intersection
    for ( int i=0; i < m_sceneMgr->getPrimitivesNum(); i++)
      {
	Primitive *pr = m_sceneMgr->getPrimitive(i);
	int res;
	if (result = pr->intersect( ray, a_Dist))
	  {
	    prim = pr;
	    result = res;
	  }
      }
    
    // no hit, terminate ray
    if (!prim)
      return 0;
    
    // handle intersection
    if (prim->isLight())
      {
	// we hit a light, stop tracing
	VECTOR3D_INITXYZ(&a_Acc,1.0f,1.0f,1.0f);
	
      }
    // hit an object
    else
      {
	Vector3 v;
	VECTOR3D_Scale(a_Dist, &(ray.getDirection()), &v );
	VECTOR3D_Add( &(ray.getOrigin()), &v, &pIntersection);
	// trace light
	for (int i=0; i<m_sceneMgr->getPrimitiveNum(); i++)
	  {
	    Primitive *p = m_sceneMgr->getPrimitive(i);
	    if (p->isLight())
	      {
		Primitive *light = p;
		// handle point light
		float shader = 1.0f;
		Vector3 l;
		Vector3 lp = ((Sphere*)light)->getCenter();
		VECTOR3D_Sub(&lp,&pIntersect,&l);
		
		float tDist = VECTOR3D_Length(&l);
		VECTOR3D_Scale(&l,1.0f/tDist);
		Vector3 temp;
		VECTOR3D_Scale(&l,0.0001f,&temp);
		VECTOR3D_Add(&temp,&pIntersect,&temp);
		// generate the shadow ray
		Ray shadowRay = Ray(temp,l);
		for (int i=0; i<m_sceneMgr->getPrimitiveNum(); i++)
		  {
		    Primitive *pr = m_sceneMgr->getPrimitive(i);
		    if ( (pr != light) && (pr->intersect(shadowRay, tDist)) )
		      {
			shade = 0;
			break;
		      }
		  }
	      }

	    // calculate diffuse shading
	    Vector3 l;
	    Vector3 lp = ((Sphere*)light)->getCenter();
	    VECTOR3D_Sub(&lp,&pIntersect,&l);
	    VECTOR3D_Normalize(&l);

	    
	    
	  }
	
      }
  }
  
}
